package com.library.library.Interceptor;

import cn.hutool.json.JSONObject;
import com.library.library.entity.User;
import com.library.library.model.Identity.KeepIdentityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Auther: 杜習田
 * @Date: 2019/12/27 09:39
 * @Description: 拦截器
 */
public class IsLoginInterceptorImpl implements HandlerInterceptor {
    @Autowired
    private KeepIdentityService keepIdentityService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("IsLoginInterceptorImpl.preHandle");
        // 该方法会在请求转发到Controller之前被执行
        if(!keepIdentityService.isIdentity("user",request)){
            response.setCharacterEncoding("UTF-8");
            JSONObject json = new JSONObject();
            json.put("status",1);
            json.put("msg","请登录！");
            response.getWriter().append(json.toString());
            return false;
        }
        // 开始
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 该方法会在Controller处理之后但是视图还没有解析的时候执行

        // 请求已经被处理
        System.out.println("IsLoginInterceptorImpl.postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 该方法会在整个请求结束（请求结束，但是并未返回给用户）之后执行


        // 整个请求结束
        System.out.println("IsLoginInterceptorImpl.afterCompletion");
    }
}
